import json
import time
from django.shortcuts import render, redirect
from IWantHotPot import settings

ALLFoodDict = {}
RoomDict = {}


@settings.UpdateID
def Index(requests):
    UserId = requests.COOKIES.get('UserID')
    RoomIdDict = []
    for RoomId in RoomDict:
        RoomIdDict.append(RoomId)
    context = {
        "UserID": UserId,
        "RoomIdDict": RoomIdDict
    }
    return render(requests, "Index.html", context)


@settings.UpdateID
def Room(requests, RoomId):
    global ALLFoodDict, RoomDict
    timenow = time.time()
    UserId = requests.COOKIES.get('UserID')

    # 如果RoomID不存在则重定向回/Room，由/Room来自己创建
    try:
        ALLFoodDict[RoomId]
    except KeyError as e:
        print(e)
        return redirect("/Room")
    UpdateRoomSuccess(RoomId)

    # 若为post的数据，更新已下锅的食材，并跳转回get
    if requests.method == 'POST':
        User = UserId
        if requests.POST["SoupBase"] == "未开始":
            ALLFoodDict[RoomId]["SoupBase"] = AllTypeDict["SoupBase"][0]
            print("添加了默认的汤底")
        else:
            ALLFoodDict[RoomId]["SoupBase"] = requests.POST["SoupBase"]
            print("添加了提供的汤底")
        # 调用UpdateFood更新下锅食材
        ALLFoodDict[RoomId]["FoodDict"][str(timenow)] = UpdateFood(requests, User, timenow, ALLFoodDict[RoomId]["SoupBase"])
        # 当用户第一次提交菜单，将用户名记录下来
        if User not in RoomDict[RoomId]["User"]:
            RoomDict[RoomId]["User"].append(User)
        print(RoomDict)
        return redirect("/Room/"+RoomId)
    print(ALLFoodDict)

    # 汤底的list下标作为汤底号码，号码发给前端，前端拼接字符获取相应的图片
    if ALLFoodDict[RoomId]["SoupBase"] in AllTypeDict["SoupBase"]:
        SoupBaseNum = str(AllTypeDict["SoupBase"].index(ALLFoodDict[RoomId]["SoupBase"]))
    else:
        SoupBaseNum = "null"
    print(SoupBaseNum)

    context = {
        "SoupBase": ALLFoodDict[RoomId]["SoupBase"],
        "SoupBaseNum": SoupBaseNum,
        "AllType": AllTypeDict,
        "UserID": UserId,
        "RoomID": RoomId,
        "ALLFoodDict": ALLFoodDict[RoomId],
        "RoomDict": RoomDict[RoomId]
    }
    return render(requests, "Room.html", context)


def GetAllType():
    with open("Index/AllType.json", 'r', encoding='utf-8') as AllTypeFile:
        AllTypeDict = json.load(AllTypeFile)
        print(AllTypeDict)
        return AllTypeDict


@settings.UpdateID
def NewRoom(requests):
    global ALLFoodDict, RoomDict
    RoomID = settings.GetNewID(2)
    ALLFoodDict[RoomID] = {
        "SoupBase": "未开始",
        "FoodDict": {},
        "Success": {}
    }
    timenow = time.time()
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timenow))
    RoomDict[RoomID] = {
        "StartTime": now,
        "EndTime": timenow + 21600,
        "User": []
    }
    return redirect("/Room/" + RoomID)


def UpdateFood(requests, User, timenow, SoupBase):
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timenow))
    NewFoodDict = {
        "添加的时间": now,
        "提交者": User
    }
    n = 0
    for Protein in AllTypeDict["Protein"]:
        if not requests.POST[Protein] == "0":
            NewFoodDict[Protein] = requests.POST[Protein]
            n += 1

    for Vegetables in AllTypeDict["Vegetables"]:
        if not requests.POST[Vegetables] == "0":
            NewFoodDict[Vegetables] = requests.POST[Vegetables]
            n += 1

    for Noodles in AllTypeDict["Noodles"]:
        if not requests.POST[Noodles] == "0":
            NewFoodDict[Noodles] = requests.POST[Noodles]
            n += 1

    if not n:
        NewFoodDict["汤底"] = SoupBase
    print("添加了这些菜：")
    print(NewFoodDict)
    return NewFoodDict


def UpdateRoomSuccess(RoomID):
    global ALLFoodDict
    tmpALLFoodDict = ALLFoodDict[RoomID]["FoodDict"].copy()
    now = time.time()
    for foodtime in tmpALLFoodDict:
        tmptime = float(foodtime) + 0.1 * 60
        if tmptime < now:
            ALLFoodDict[RoomID]["Success"][foodtime] = ALLFoodDict[RoomID]["FoodDict"][foodtime]
            del ALLFoodDict[RoomID]["FoodDict"][foodtime]


def SearchRoom(requests):
    if requests.method == 'POST':
        return redirect("/Room/"+ requests.POST["RoomId"])
    else:
        return redirect("/")


# def UpdateRoomSuccess(RoomID):
#     global ALLFoodDict
#     now = time.time()
#     for RoomID, Food in ALLFoodDict.items():
#         for foodtime in Food["FoodDict"]:
#             tmptime = float(foodtime) + 1 * 60 * 60
#             if tmptime < now:
#                 ALLFoodDict[RoomID]["Success"][foodtime] = ALLFoodDict[RoomID]["FoodDict"][foodtime]
#                 del ALLFoodDict[RoomID]["FoodDict"][foodtime]


AllTypeDict = GetAllType()
